import 'package:flutter/material.dart';

import 'package:get/get.dart';

import 'package:sainbainu/common/values/colors.dart';
import 'package:sainbainu/common/values/sizes.dart';
import 'package:sainbainu/common/widgets/widget.dart';
import 'package:sainbainu/view/group_detail/controller.dart';

class CustomSliverHeader extends GetView<GroupDetailController> {
  final VoidCallback onBack;
  final VoidCallback onJoinTap;
  final VoidCallback onEditTap;
  final VoidCallback onMemberTap;

  const CustomSliverHeader({
    super.key,
    required this.onBack,
    required this.onJoinTap,
    required this.onEditTap,
    required this.onMemberTap,
  });

  @override
  Widget build(BuildContext context) {
    return _buildSliverAppBar();
  }

  /// 头部
  _buildSliverAppBar() {
    return SliverAppBar(
      leading: Obx(
        () => IconButton(
          onPressed: onBack,
          icon: Icon(
            Icons.arrow_back_ios_new_rounded,
            color: controller.state.isCollapsed.value
                ? Colors.black
                : Colors.white,
          ),
        ),
      ),
      title: Obx(
        () => Opacity(
          opacity: controller.state.titleOpacity.value,
          child: Text(controller.state.groupDetail.groupName ?? ''),
        ),
      ),
      actions: [
        Obx(
          () => AnimatedScale(
            scale: controller.state.isCollapsed.value ? 1 : 0,
            duration: const Duration(milliseconds: 300),
            curve: Curves.easeInOut,
            child: _buildPopupMenu(),
          ),
        ),
      ],
      pinned: true,
      stretch: true,
      expandedHeight: kGroupCoverHeight,
      flexibleSpace: FlexibleSpaceBar(
        collapseMode: CollapseMode.pin,
        background: GetBuilder<GroupDetailController>(
          id: 'groupDetail',
          builder: (_) => _buildContent(),
        ),
      ),
    );
  }

  /// 弹出菜单
  Widget _buildPopupMenu() {
    return GetBuilder<GroupDetailController>(
      id: 'groupDetail',
      builder: (_) {
        if (_.state.groupDetail.creatorFlag == 1) {
          return PopupMenuButton<String>(
            iconSize: 24,
            offset: const Offset(0, 40),
            surfaceTintColor: Colors.white,
            color: Colors.white,
            elevation: 10.0,
            shadowColor: Colors.black.withOpacity(0.5),
            shape:
                RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
            itemBuilder: (context) {
              return <PopupMenuEntry<String>>[
                PopupMenuItem<String>(
                  value: 'edit',
                  onTap: onEditTap,
                  child: Text('信息编辑'.tr),
                ),
                PopupMenuItem<String>(
                  value: 'member',
                  onTap: onMemberTap,
                  child: Text('成员管理'.tr),
                ),
              ];
            },
          );
        } else {
          return IconButton(
            onPressed: onMemberTap,
            icon: const Icon(
              Icons.more_horiz_rounded,
              size: 24,
            ),
          );
        }
      },
    );
  }

  /// 内容
  Widget _buildContent() {
    return Stack(
      fit: StackFit.expand,
      children: [
        Hero(
          tag: '${controller.state.uniqueTag}_${controller.state.groupId}',
          child: CustomImage(
            url: controller.state.groupCover ??
                controller.state.groupDetail.cover ??
                '',
            width: Get.width,
          ),
        ),
        AnimatedOpacity(
          opacity: controller.state.showHeaderInfo ? 1.0 : 0.0,
          duration: const Duration(milliseconds: 600),
          curve: Curves.easeInToLinear,
          child: Container(color: Colors.black.withOpacity(0.3)),
        ),
        Positioned(
          left: 20,
          right: 20,
          bottom: 8,
          child: AnimatedOpacity(
            opacity: controller.state.showHeaderInfo ? 1.0 : 0.0,
            duration: const Duration(milliseconds: 600),
            curve: Curves.easeInToLinear,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                _buildTitleBtnWrap(),
                const SizedBox(height: 10),
                _buildNumTextRow(),
                const SizedBox(height: 10),
                _buildIntro(),
              ],
            ),
          ),
        ),
      ],
    );
  }

  /// 标题、按钮
  Widget _buildTitleBtnWrap() {
    return Row(
      children: [
        Expanded(
          child: Text(
            controller.state.groupDetail.groupName ?? '',
            style: const TextStyle(
              color: Colors.white,
              fontSize: 18,
              fontWeight: FontWeight.w600,
            ),
          ),
        ),
        Obx(() => _buildRightBtn()),
      ],
    );
  }

  /// 右侧按钮
  Widget _buildRightBtn() {
    String text;
    VoidCallback onTap;

    if (controller.state.groupDetail.creatorFlag == 1) {
      text = '编辑小组'.tr;
      onTap = onEditTap;
    } else {
      text = controller.state.isJoin.value ? '退出小组'.tr : '加入小组'.tr;
      onTap = onJoinTap;
    }

    return SizedBox(
      width: 90,
      height: 34,
      child: ElevatedButton(
        onPressed: onTap,
        style: ElevatedButton.styleFrom(
          backgroundColor: const Color.fromRGBO(255, 255, 255, 0.7),
          foregroundColor: Colors.white,
          padding: const EdgeInsets.symmetric(horizontal: 0),
          elevation: 0,
        ),
        child: Text(
          text,
          style: const TextStyle(color: AppColors.active),
        ),
      ),
    );
  }

  /// icon 数量
  Widget _buildNumTextRow() {
    return Row(
      children: [
        _buildNumTextItem(
          num: (controller.state.groupDetail.memberNum ?? 0).toDouble(),
          label: '${'成员'.tr}：',
          icon: Icons.group_add_sharp,
          onTap: onMemberTap,
        ),
        Container(
          width: 0.5,
          height: 12,
          color: Colors.white,
          margin: const EdgeInsets.symmetric(horizontal: 10),
        ),
        _buildNumTextItem(
          num: (controller.state.groupDetail.noteNum ?? 0).toDouble(),
          label: '${'帖子'.tr}：',
          icon: Icons.description_rounded,
        ),
        Container(
          width: 0.5,
          height: 12,
          color: Colors.white,
          margin: const EdgeInsets.symmetric(horizontal: 10),
        ),
        _buildNumTextItem(
          num: (controller.state.groupDetail.commentNum ?? 0).toDouble(),
          label: '${'评论'.tr}：',
          icon: Icons.comment_rounded,
        ),
      ],
    );
  }

  /// 点赞 收藏每一项
  Widget _buildNumTextItem({
    required double num,
    required String label,
    required IconData icon,
    VoidCallback? onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Row(
        children: [
          Icon(icon, color: const Color(0xffFCFCFC), size: 16),
          const SizedBox(width: 4),
          Text(
            label,
            style: const TextStyle(
              color: Color(0xffFCFCFC),
              fontSize: 14,
            ),
          ),
          Text(
            '$num',
            style: const TextStyle(
              color: Color(0xffFCFCFC),
              fontSize: 14,
            ),
          ),
        ],
      ),
    );
  }

  /// 介绍
  Widget _buildIntro() {
    return SizedBox(
      height: 62,
      child: Text(
        controller.state.groupDetail.intro ?? '',
        maxLines: 3,
        overflow: TextOverflow.ellipsis,
        style: const TextStyle(
          color: Color(0xffFCFCFC),
          fontSize: 12,
          fontWeight: FontWeight.w500,
        ),
      ),
    );
  }
}
